package org.wx.io.netty.rpc.proxy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultEventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.wx.io.netty.rpc.client.RpcClient;
import org.wx.io.netty.rpc.protocol.MyContent;
import org.wx.io.netty.rpc.protocol.MyHeader;
import org.wx.io.netty.rpc.protocol.PackMsg;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;

/**
 * @description:
 * @author: wangxun
 * @createDate: 2021/2/23
 * @version: 1.0
 */
@Slf4j
public class ProxyInvokeHandler implements InvocationHandler {


    private ChannelHandlerContext ctx;

    public ProxyInvokeHandler(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        log.info("调用代理对象，请求的方法是:{}",method.getName());
        MyContent myContent = new MyContent();
        myContent.setName(method.getDeclaringClass().getName());
        myContent.setMethodName(method.getName());
        myContent.setParameterTypes(method.getParameterTypes());
        myContent.setParameters(args);

        MyHeader myHeader = MyHeader.createHeader();
        // 构建消息，并发送
        PackMsg packMsg = new PackMsg(myHeader,myContent);

        ctx.writeAndFlush(packMsg);
        // 构建异步返回
        CompletableFuture cf = new CompletableFuture();
        RpcClient.futureMap.put(myHeader.getRequestId(),cf);

       return cf.get();

    }


}
